import FormLayout from "@/components/forms/formLayout"
import styled from "@emotion/styled"
import EasyFormProvider from "@/components/forms/EasyFormProvider"
import _ from "lodash"
import { useRef, useEffect, useState } from "react"
import { useParams, useSearchParams } from "react-router-dom"
import { Repository } from "@/atoms/api_repositories"
import { useAuth } from "@/features/useAuth"
// import { useAtomValue } from "jotai"
// import { verifyAtom } from "@/pages/AccountPage/atoms/verify"
import { useAtom } from "jotai"
import { SetInitVerifyAtom, SetVerifyAtom, verifyAtom } from "@/pages/AccountPage/atoms/verify"
import { useNavigate } from "react-router-dom"
import ApiFetchers from "@/apis/api_fetchers"
import { toast } from "react-toastify"
import Svg from "@/components/base/Svg"

const FormBox = styled.div`
    width: 100%;
    margin-top: 40rem;
    display: flex;
    flex-direction: column;
    position: relative;
`
const VerifyMessage = styled.p`
    display: none;
    position: absolute;
    left: 0;
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 12rem;
    line-height: 16rem;
    letter-spacing: 0;
    color: #fb2d60;
    padding-left: 20rem;

    & > em {
        content: "";
        position: absolute;
        display: block;
        width: 16rem;
        height: 16rem;
        top: 0;
        left: 0;
    }

    &.stepNextvm {
        display: block;
        position: initial;
        margin: 0;
        padding: 0;
    }

    &.stepNextvm::before {
        display: none;
    }

    &.codemsg {
        position: absolute;
        margin: 0;
        top: 60rem;
        left: 0;
    }

    &.codemsg.setp {
        //bottom: 25rem;
        bottom: auto;
        top: 52rem;
    }

    &.codemsg.error {
        display: block;
    }
`

interface CodeProps {
    code: string
}
const sleep = (delay: number | undefined) => new Promise((resolve) => setTimeout(resolve, delay))

const Verify = () => {
    // 获取url中的参数
    const [searchParams] = useSearchParams()
    // const verifyData = useAtomValue(verifyAtom)
    const [verifyData] = useAtom(verifyAtom)
    const [, setVerifyData] = useAtom(SetVerifyAtom)
    const [, setInitVerifyData] = useAtom(SetInitVerifyAtom)
    // 当前方式需要修改
    const verifyMethod = verifyData?.verifyMethod ? verifyData?.verifyMethod : verifyData?.field
    // 获取用户信息
    const navigator = useNavigate()
    const { data: userInfo } = Repository.useUserInfo()
    const otpId = verifyData?.otpId
    const type = verifyData?.type
    const { loginWithOtp, sendVerifyCode } = useAuth()
    const [VerifyError, setVerifyError] = useState({
        state: false,
        error: "",
    })

    const phoneNumber = verifyData?.phone ? verifyData?.phone : userInfo?.phoneNumber?.number
    const emailAddress = verifyData?.email ? verifyData?.email : userInfo?.email
    useEffect(() => {
        if (!otpId) {
            setInitVerifyData()
            navigator("/s-account")
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [otpId])

    const verifyCode = async (code: string) => {
        if (!otpId) return
        const params = {
            code: code,
            phone: phoneNumber ?? "",
            country_code: "63",
            otp_id: otpId,
        }
        const res = await ApiFetchers.refPostAuthSms(params)
        return res
    }

    const getSmsCode = async () => {
        const res = await sendVerifyCode(phoneNumber ?? "")
        return res
    }
    const handleConfirm = async (data: string) => {
        // console.log(data, "data")
        //preact只传data
        if (!data) return

        // 提交验证码
        // const res = await verifyCode(data.code)
        const res = await verifyCode(data)
        if (res) {
            // 验证成功
            //这里用手机验证码去改变密码的直接把验证码记录下来就可以去设置密码页面了
            setVerifyData({
                ...verifyData,
                code: data,
            })
            if (type === "forget") {
                navigator("/forgetPassword/verify/verifypassword")
            } else {
                if (verifyData?.field === "email") {
                    navigator("/s-account/form/email")
                } else if (verifyData?.field === "password") {
                    navigator("/s-account/form/password")
                } else {
                    navigator("/s-account/form/phone")
                }
            }
        } else {
            toast("Please enter the correct code")
            setVerifyError({
                state: true,
                error: "Please enter the correct code",
            })
        }
    }

    const throttledSubmit = _.throttle(handleConfirm, 2000, { trailing: false })
    const codeRef = useRef(null)
    const description =
        verifyMethod === "email"
            ? `We'll send a verification code to your email: ${emailAddress}`
            : `We'll send a verification code to your mobile: +${userInfo?.phoneNumber?.countryCode ?? "63"}${phoneNumber}`
    const isEmailForget =
        verifyData && verifyData?.field === "email" && verifyData?.type === "forget"
    const isPhoneForget =
        verifyData && verifyData?.field === "phone" && verifyData?.type === "forget"
    const onBack = () => {
        console.log("onBack")

        if (isPhoneForget) {
            navigator("/forgetPassword/verify/phone")
        } else if (isEmailForget) {
            navigator("/forgetPassword/verify/email")
        } else {
            navigator(-1)
        }
        // setInitVerifyData()
    }
    console.log(verifyData, "verifyData", { phoneNumber, emailAddress })
    return (
        <FormLayout
            title="Enter the code"
            description={description}
            backPath="/verifytype"
            onBack={onBack}
        >
            <FormBox>
                <EasyFormProvider
                    showSubmitButton={false}
                    // @ts-ignore
                    onSubmit={throttledSubmit}
                    queryList={["verify", "submitButton"]}
                    ref={codeRef}
                    sendCode={getSmsCode}
                />
                <VerifyMessage className={`codemsg ${VerifyError?.state ? " error " : ""}`}>
                    <em>
                        <Svg src={"components/form_item/public_fail_icon.svg"} />
                    </em>
                    {VerifyError?.error ?? "Please enter the correct code"}
                </VerifyMessage>
            </FormBox>
        </FormLayout>
    )
}

export default Verify
